import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Input, Select, Modal, message, Spin } from 'antd';
import request from '@/utils/request';
import ComponentAttrInfo from './ComponentAttrInfo';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const namespace = 'componentManage';

function ComponentAdd(props) {
  const { getFieldDecorator } = props.form;
  const [componentTypeList, setComponentTypeList] = useState([]); // 组件类型
  const [spinning, setSpinning] = useState(false);

  useEffect(() => {
    initData();
  }, [props.selectComponent]);

  const initData = () => {
    getComponentTypeList();
    if (props.componentAddType === 'add') {
      props.form.setFieldsValue({
        componentType: '1100',
      });
    } else if (props.componentAddType === 'modify') {
      props.form.setFieldsValue({
        componentId: props.selectComponent.componentId,
        componentName: props.selectComponent.componentName,
        componentCode: props.selectComponent.componentCode,
        componentType: props.selectComponent.componentType,
      });
    }
  };

  const getComponentTypeList = () => {
    const tempObjTypeList = [
      {
        name: '标准组件',
        value: '1000',
      },
      {
        name: '个性化组件',
        value: '1100',
      },
    ];
    setComponentTypeList(tempObjTypeList);
  };

  // dva 保存选中的组件
  const saveSelectComponent = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectComponent`,
      payload: params,
    });
  };

  // dva 保存新增组件弹窗显示/隐藏标记
  const saveComponentAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAddVisibleFlag`,
      payload: params,
    });
  };

  // dva 保存新增组件类型
  const saveComponentAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAddType`,
      payload: params,
    });
  };

  // dva 保存组件属性数据列表
  const saveComponentAttrAddList = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAttrAddList`,
      payload: params,
    });
  };

  const clearPropStates = () => {
    saveComponentAddVisibleFlag(false);
    saveComponentAddType('');
    saveComponentAttrAddList([]);
    saveSelectComponent({});
  };

  // 新增/修改组件
  const handleOk = () => {
    props.form.validateFields((err, formData) => {
      if (err) return;

      setSpinning(true);
      formData.componentAttrList = props.componentAttrAddList;

      if (props.componentAddType === 'add') {
        request('pmc/pcms/component/add', { data: formData }).then(res => {
          if (res && res.success === true) {
            setSpinning(false);
            message.success('新增成功');
            clearPropStates();
          } else {
            setSpinning(false);
            if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('新增失败');
            }
          }
        });
      } else if (props.componentAddType === 'modify') {
        request('pmc/pcms/component/update', { data: formData }).then(res => {
          if (res && res.success === true) {
            setSpinning(false);
            message.success('修改成功');
            clearPropStates();
          } else {
            setSpinning(false);
            if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('修改失败');
            }
          }
        });
      }
    });
  };

  const handleCancel = () => {
    saveComponentAddVisibleFlag(false);
    clearPropStates();
  };

  return (
    <Modal
      title={props.componentAddType === 'add' ? '新增自定义组件' : '修改自定义组件'}
      visible={props.modalVisible}
      width="80%"
      height="70%"
      destroyOnClose
      onCancel={() => {
        handleCancel();
      }}
      onOk={() => {
        handleOk();
      }}
    >
      <Spin spinning={spinning}>
        <Form>
          <Row>
            <Col span={12}>
              <Form.Item label="组件名称" {...formItemLayout}>
                {getFieldDecorator('componentName', {
                  rules: [
                    {
                      required: true,
                      message: '组件名称不能为空',
                    },
                  ],
                })(
                  <Input
                    placeholder="请输入组件名称"
                    disabled={
                      !(props.componentAddType === 'add' || props.componentAddType === 'modify')
                    }
                    maxLength={20}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="组件编码" {...formItemLayout}>
                {getFieldDecorator('componentCode', {
                  rules: [
                    {
                      required: true,
                      message: '组件编码不能为空',
                    },
                  ],
                })(
                  <Input
                    placeholder="请输入组件编码"
                    disabled={
                      !(props.componentAddType === 'add' || props.componentAddType === 'modify')
                    }
                    maxLength={30}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="组件类型" {...formItemLayout}>
                {getFieldDecorator('componentType')(
                  <Select style={{ width: '100%' }} showSearch disabled allowClear>
                    {componentTypeList.length
                      ? componentTypeList.map(item => {
                          return (
                            <Select.Option value={item.value} key={item.value}>
                              {item.name}
                            </Select.Option>
                          );
                        })
                      : null}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ display: 'none' }}>
            <Col span={1}>
              <Form.Item label="组件Id" {...formItemLayout}>
                {getFieldDecorator('componentId')(<Input disabled />)}
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <ComponentAttrInfo />
      </Spin>
    </Modal>
  );
}

export default connect(({ componentManage }) => ({
  selectComponent: componentManage.selectComponent,
  componentAddType: componentManage.componentAddType,
  selectComponentAddFlag: componentManage.selectComponentAddFlag,
  componentAttrAddList: componentManage.componentAttrAddList,
}))(Form.create()(ComponentAdd));
